package com.itheima.service;



import com.alibaba.dubbo.common.json.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UsersMapper;
import com.itheima.pojo.Users;
import com.itheima.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Service
public class UserService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public PageResult findAll(Integer page, Integer pageSize) throws IOException {
        //设置当前页数和当前页多少条数据
        IPage<Users> ipage = new Page(page,pageSize);

        usersMapper.selectPage(ipage, null);

        PageResult pageResult = new PageResult();

        List<Users> items = ipage.getRecords();//当前页的数据
        Integer pages = Math.toIntExact(ipage.getPages());//总页数
        Integer counts = Math.toIntExact(ipage.getTotal());//总记录数
        Integer pagesize = Math.toIntExact(ipage.getSize());//页大小


        pageResult.setPage(page);
        pageResult.setCounts(counts);
        pageResult.setItems(items);
        pageResult.setPages(pages);
        pageResult.setPagesize(pagesize);
        //讲对象转化为json字符串
        String json = JSON.json(pageResult);
        //存到redis中
        this.redisTemplate.opsForValue().set("paging",json);

        return pageResult;


    }


    public Users find(Integer Id) throws IOException {
        //获取users
        Users users = this.usersMapper.selectById(Id);
        //讲对象转化为json字符串
        String json = JSON.json(users);
        //存入到redis中
        this.redisTemplate.opsForValue().set("user",json);
        return users;
    }

}